package Main
{
	import flash.events.Event;
	import flash.utils.ByteArray;
	
	import mx.collections.ArrayCollection;
	import mx.collections.ArrayList;
	import mx.controls.Alert;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	
	import singleton.ATLSingleton;
	import singleton.GUIController;
	import singleton.Session;

	public class WSControllerFacade
	{
		private static var fileKeepers:FileReferenceHandlers = FileReferenceHandlers.getInstance();;
		private static var controller:GUIController = GUIController.getInstance();
		private static var atl:ATLSingleton = ATLSingleton.getInstance();
		private static var session:Session = Session.getInstance();
		private static var atlCodes:ArrayList;
		private static var DELIMITER:String = " ";
		
		public function WSControllerFacade() {}
		
		public static function M2MTransformationService_faultHandler(event:FaultEvent):void {
			if (event.fault.toString().indexOf("Security") != -1 || event.fault.toString().indexOf("security") != -1) {
				Alert.show("Could not connect to the server. Security issue detected.", "Error");
			} else if (event.fault.toString().indexOf("Server.Error.Request") != -1) {
				Alert.show("Server is offline. Try again later.", "Error");
				
			} else {
				Alert.show("An internal error happened. Try again later.", "Error");
			}
		}
		
		public static function uploadATLFile_faultHandler(event:FaultEvent):void {
			controller.getProgressBar(GUIController.UPLOAD).setVisible(false);
			if (event.fault.faultString.search("Error: 9") != -1) {
				controller.getWebService().getNewSessionId();
				Alert.show("Session expired! Try again now.");
			} else if (event.fault.faultString.search(Util.ERR_CODE_ATL_SYNTAX) != -1) {
				Alert.show("Syntax error!");
			} else if (event.fault.faultString.search(Util.ERR_CODE_MISSING_MM) != -1 ) {
				
			} else {
				controller.restartTimer();
				Alert.show("The file uploaded isn't an ATL file or has syntax errors.", "Error");
			}
			
		}
		
		public static function uploadATLFile_resultHandler(event:ResultEvent):void {
			controller.restartTimer();
			var id:String = event.result as String;
			
			UploadHandler.toggleProgressBar(false);
			UploadHandler.setATLFileID(id);
			UploadHandler.askForMetamodels();
			
			
		}
		
		public static function uploadMetamodel_faultHandler(event:FaultEvent):void {
			
			if (event.fault.faultString.search("Error: 9") != -1) {
				controller.getWebService().getNewSessionId();
				Alert.show("Error while uploading the metamodel. Session expired.");
			} else {
				controller.restartTimer();
				Alert.show("Error while uploading the metamodel");
				
			}
			UploadHandler.getMetamodelId().removeAll();
			UploadHandler.toggleProgressBar(false);
			
		}
		
		public static function uploadMetamodel_resultHandler(event:ResultEvent):void {
			UploadHandler.setMetamodelID(event.result as String);
			
		}
		
		public static function uploadSourceModel_faultHandler(event:FaultEvent):void {
			
			if (event.fault.faultString.search("Error: 9") != -1) {
				controller.getWebService().getNewSessionId();
				Alert.show("Error while uploading the source model. Session expired.");
			}
		}
		
		public static function uploadSourceModel_resultHandler(event:ResultEvent):void {
			controller.restartTimer();
			var sourceModelId:String = event.result as String;
			//Verificar como enviar os metamodelos corretamente
			//controller.getWebService().executeTransformation(session.getId(), atl.getCurrentId(), UploadHandler.getTargetMetamodelsId(), UploadHandler.getMetamodelId().getItemAt(1), sourceModelId, atl.getATLRules());
			controller.getWebService().executeTransformation(session.getId(), atl.getCurrentId(), UploadHandler.getMetamodelId().getItemAt(0), UploadHandler.getMetamodelId().getItemAt(1), sourceModelId, atl.getATLRules());
		}
		
		public static function getATLInformation_resultHandler(event:ResultEvent):void {
			var result:String = event.result as String;
			controller.restartTimer();
			if (result.indexOf(Util.NAME) == 0) {
				var code:String = "";
				if (atlCodes.length > 0) {
					code = atlCodes.removeItemAt(0) as String;
					if (atlCodes.length > 0)
						controller.getWebService().getATLInformation(session.getId(), atlCodes.getItemAt(0), Util.NAME);
				}
				if (TransformationHandler.atlNames.getItemIndex(result.replace(Util.NAME + DELIMITER, "")) == -1 ) {
					TransformationHandler.atlNames.addItem(result.replace(Util.NAME + DELIMITER, ""));
					TransformationHandler.setDataProviderForDataGrid(GUIController.ATL_FILE, TransformationHandler.atlNames);
				}
				
				TransformationHandler.allATLID[result.replace(Util.NAME + DELIMITER, "")] = code;
				
				
				if (controller.getTextInput(GUIController.ATL_FILE) != null && controller.getTextInput(GUIController.ATL_FILE).text != "ATL Transformation") {
					if (TransformationHandler.selectTransformationByName(result.replace(Util.NAME + DELIMITER, ""))) {
						UploadHandler.resetField(GUIController.ATL_FILE);
						UploadHandler.resetField(GUIController.SRC_METAMODEL);
						UploadHandler.resetField(GUIController.TRGT_METAMODEL);
					}
				}
				
			} else if (result.indexOf(Util.CONTENT) == 0) {
				var bArray:ByteArray = new ByteArray();
				bArray.writeUTFBytes(result.replace(Util.CONTENT, ""));
				controller.showPopUpString(result.replace(Util.CONTENT, ""));
			} else if (result.indexOf(Util.CREATION_DATE) == 0) {
				//creation date
			} else if (result.indexOf(Util.ATL_SOURCE_METAMODEL) == 0) {
				if (controller.getCurrentState() == "Uploading") {
					UploadHandler.changeMetamodelInputText(GUIController.SRC_METAMODEL, result.replace(Util.ATL_SOURCE_METAMODEL + DELIMITER, ""));
				} else {
					TransformationHandler.changeModelLabel(GUIController.SRC_METAMODEL, result.replace(Util.ATL_SOURCE_METAMODEL + DELIMITER, ""));
				}
			} else if (result.indexOf(Util.ATL_SOURCE_MODEL) == 0) {
				TransformationHandler.changeModelLabel(GUIController.SRC_MODEL, result.replace(Util.ATL_SOURCE_MODEL + DELIMITER, ""));
			} else if (result.indexOf(Util.ATL_TARGET_METAMODEL) == 0) {
				if (controller.getCurrentState() == "Uploading") {
					UploadHandler.changeMetamodelInputText(GUIController.TRGT_METAMODEL, result.replace(Util.ATL_TARGET_METAMODEL + DELIMITER, ""));
				} else {					
					TransformationHandler.changeModelLabel(GUIController.TRGT_METAMODEL, result.replace(Util.ATL_TARGET_METAMODEL + DELIMITER, ""));
				}
			} else if (result.indexOf(Util.ATL_TARGET_MODEL) == 0) {
				//modelo de saida
			} else if (result.indexOf(Util.ATL_RULES) == 0) {
				var array:Array;
				array = result.replace("[", "").replace("]", "").replace(Util.ATL_RULES, "").split(",");
				var rules:ATLRules = new ATLRules(array);
				TransformationHandler.setDataProviderForDataGrid(GUIController.RULES, rules.getRules()); 
			}
		}
		
		public static function getATLInformation_faultHandler(event:FaultEvent):void {
			
			if (event.fault.faultString.search("Error: 9") != -1) {
				controller.getWebService().getNewSessionId();
				
			}
		}
		
		public static function getAllMetamodels_resultHandler(event:ResultEvent):void {
			//TODO
		}
		
		public static function getMetamodelInformation_resultHandler(event:ResultEvent):void {
			
		}
		
		public static function getMetamodelInformation_faultHandler(event:FaultEvent):void {
			
			if (event.fault.faultString.search("Error: 9") != -1) {
				controller.getWebService().getNewSessionId();
				
			}
		}
		
		public static function getModelInformation_resultHandler(event:ResultEvent):void {
			controller.restartTimer();
			var result:String = event.result as String;
			if (result.indexOf(Util.CONTENT) == 0) {
				TransformationHandler.transformationComplete();
				var bArray:ByteArray = new ByteArray();
				bArray.writeUTFBytes(result.replace(Util.CONTENT, ""));
				
				TransformationHandler.receiveResultContent(bArray);
			}
			
		}
		
		public static function getModelInformation_faultHandler(event:FaultEvent):void {
			
			if (event.fault.faultString.search("Error: 9") != -1) {
				controller.getWebService().getNewSessionId();
				
			}
		}
		
		public static function getATLRuleDependencies_resultHandler(event:ResultEvent):void {
			controller.restartTimer();
			var result:String = (event.result as String).replace(" ", "").replace("[", "").replace("]","");
			var array:Array = result.split(",");
			var i:int, tam:int = array.length;
			if (controller.getDataGrid(GUIController.RULES).selectedIndices.length > 1) {
				
				for (i = 0; i < tam; i++) {
					var rule:String = (array.pop() as String).replace(" ", "");
					if (controller.getTextInput(GUIController.RULES).text.indexOf(rule) == -1)
						controller.getTextInput(GUIController.RULES).text += (rule) + "\n";
				}
			} else {
				controller.getTextInput(GUIController.RULES).text = "";
				for (i = 0; i < tam; i++) {
					controller.getTextInput(GUIController.RULES).text += (array.pop() as String) + "\n";
				}
			}
		}
		
		public static function getATLRuleDependencies_faultHandler(event:FaultEvent):void {
			
			if (event.fault.faultString.search("Error: 9") != -1) {
				controller.getWebService().getNewSessionId();
				
			}
		}
		
		public static function getNewSessionId_resultHandler(event:ResultEvent):void {
			session.setId(event.result as String);
			controller.restartTimer();
		}
		
		public static function getAllATLTransformations_resultHandler(event:ResultEvent):void {
			controller.restartTimer();
			try {
				if (event.result == null)
					return;
				
				var result:String = (event.result as String).replace(" ", "").replace("[", "").replace("]","");
				var array:Array = result.split(",");
				var i:int, tam:int = array.length;
				//TransformationHandler.atlNames.removeAll();
				//TransformationHandler.allATLID = new ArrayCollection(array.slice());
				atlCodes = new ArrayList(array.slice());
				
				
				controller.getWebService().getATLInformation(session.getId(), atlCodes.getItemAt(0), Util.NAME);
				
				
				
				
			} catch (err:Error){
				Alert.show("Error while trying to retrieve transformation data");
				Alert.show(err.toString());
				
			}
		}
		
		public static function getTransformations_faultHandler(event:FaultEvent):void {
			if (event.fault.faultString.search("Error: 9") != -1) {
				controller.getWebService().getNewSessionId();
				
			}
		}
		
		public static function executeTransformation_resultHandler(event:ResultEvent):void {
			
			controller.getWebService().getModelInformation(session.getId(), event.result as String, Util.CONTENT);
			controller.restartTimer();
			
		}
		
		public static function executeTransformation_faultHandler(event:FaultEvent):void {
			controller.getProgressBar(GUIController.EXECUTE).setVisible(false);			
			if (event.fault.faultString.search("Error: 9") != -1) {
				controller.getWebService().getNewSessionId();
				Alert.show("The transformation could not be completed. Session expired.");
			} else if (event.fault.faultString.search("Missing") != -1) {
				Alert.show("Some rules have dependencies. Select them.");
			} else if (event.fault.faultString.search(Util.ERR_CODE_INCOMPATIBLE_ARTIFACTS) != -1) {

				Alert.show("The transformation could not be completed. Some uploaded artifacts are incompatible.", "Error");
			}
		}
		
		
		
	}
}